import { Modal, Button, Form, Input, message } from 'antd';
import React, { useState } from 'react';
import store from "../../store";
import { addBanner } from "../../http/request";

const App = () => {
    //控制弹窗显示
    const [open, setOpen] = useState(store.getState());
    store.subscribe(() => {
        setOpen(state => {
            return store.getState()
        })
    })
    //取消弹窗
    const handleCancel = () => {
        store.dispatch({
            type: "open",
            data: false
        })
    };
    //提交表单
    const onFinish = (values) => {
        console.log('Success:', values);
        setTimeout(() => {
            addBanner(values).then(res => {
                // console.log(res);
                const { code } = res.data
                if (code == 200) {
                    message.success("添加成功")
                    window.location.reload()
                } else {
                    message.error("添加失败")
                }
            })
            store.dispatch({
                type: "open",
                data: false
            })
            
        }, 1000);
    };
    //提交失败
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <>
            <Modal
                title="添加轮播图"
                open={open.open}
                width={700}
                footer={null}
                onCancel={handleCancel}
            >
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="图片链接"
                        name="img"
                        rules={[{ required: true, message: '请输入图片链接' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="提示信息"
                        name="alt"
                        rules={[{ required: true, message: '请输入提示信息' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="链接地址"
                        name="link"
                        rules={[{ required: true, message: '请输入链接地址' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            添加
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default App;